基礎使用可以看一下之前寫的文章 Angular6之表單-簡易Reactive Form
https://ithelp.ithome.com.tw/articles/10205937
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<div class="form-row">
<div class="form-group col-md-6 text-left">
<label for="name">姓名 <span class="text-danger">*</span> </label>
<input type="text" class="form-control" id="name" placeholder="請輸入姓名" name="name" formControlName="name">
</div>
<div class="form-group col-md-6 text-left">
<label for="job">職業 <span class="text-danger">*</span> </label>
<input type="text" class="form-control" id="job" placeholder="請輸入職業" name="job" formControlName="job">
</div>
</div>
<button type="button" class="btn btn-master" (click)="addFormControl()">添加 FormControl</button>
<button type="button" class="btn btn-master" (click)="removeFormControl()">移除 FormControl</button>
<button type="button" class="btn btn-master" (click)="setFormControl()">重新設定 email FormControl</button>
<button type="button" class="btn btn-master" (click)="containsEmail()">判別 email 是否活躍</button>
<button type="button" class="btn btn-master" (click)="setValue()">設定資料值</button>
<button type="button" class="btn btn-master" (click)="setPatchValue()">設定部分資料值</button>
<button type="button" class="btn btn-master" (click)="resetValue()">清空資料</button>
Form value: {{form.value | json}}
Form getRawValue(): {{form.getRawValue() | json}}
</form>
form = new FormGroup({
name: new FormControl(''),
job: new FormControl({value: '', disabled: true}),
});
get name() {
return this.form.get('name') as FormControl;
}
get job() {
return this.form.get('job') as FormControl;
}
addFormControl() {
this.form.addControl('email', new FormControl(''));
}
removeFormControl() {
this.form.removeControl('email');
}
setFormControl() {
this.form.setControl('email', new FormControl('a123456@gmail.com'));
}
containsEmail() {
alert(`email 目前狀態是 :${this.form.contains('email')}`);
}
setValue() {
this.form.setValue({
name: '馬達',
job: '工程師',
email: 'moda@gmail.com'
});
}
setPatchValue() {
this.form.patchValue({
email: 'omg@gmail.com'
});
}
resetValue() {
this.form.reset();
}